<template>
  <div class="admin-page">
    <div class="page-header">
      <h1 class="page-title">公司概览</h1>
      <p class="page-subtitle">管理员视角：全公司团队与近期活动</p>
    </div>
    <el-card class="content-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">关键指标（近 {{ days }} 天）</span>
          <div class="header-actions">
            <el-select v-model="days" size="small" style="width: 120px" @change="load">
              <el-option :value="7" label="近7天" />
              <el-option :value="14" label="近14天" />
              <el-option :value="30" label="近30天" />
            </el-select>
          </div>
        </div>
      </template>

      <el-row :gutter="16">
        <el-col :xs="24" :sm="12" :md="8">
          <el-card shadow="hover" class="kpi-card"><div class="kpi-num">{{ stats.teamCount }}</div><div class="kpi-title">团队数量</div></el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-card shadow="hover" class="kpi-card"><div class="kpi-num">{{ stats.scheduleCount }}</div><div class="kpi-title">日程数量</div></el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-card shadow="hover" class="kpi-card"><div class="kpi-num">{{ stats.worklogCount }}</div><div class="kpi-title">工作日志（总计）</div></el-card>
        </el-col>
      </el-row>

      <div class="trend-wrap">
        <div class="trend-title">近期工作日志趋势</div>
        <div class="bars">
          <div v-for="(p,i) in trend" :key="i" class="bar">
            <div class="bar-col" :style="{ height: Math.max(6, (p.worklogs || 0) * scale) + 'px' }" />
            <div class="bar-label">{{ p.date }}</div>
          </div>
        </div>
      </div>

      <div class="teams-wrap">
        <div class="teams-title">团队列表（{{ teams.length }}）</div>
        <el-table :data="teams" size="small" v-loading="loading">
          <el-table-column prop="teamId" label="#" width="80" />
          <el-table-column prop="teamName" label="团队名称" />
          <el-table-column prop="description" label="描述" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
        </el-table>
      </div>

      <el-divider />
      
      <!-- 公司看板展示区域 -->
      <div class="company-kanban-section">
        <el-card class="kanban-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">公司看板概览</span>
              <el-button type="primary" size="small" :icon="Refresh" @click="refreshKanbanData">刷新</el-button>
            </div>
          </template>
          <div class="kanban-stats">
            <div class="kanban-stat-item">
              <div class="stat-icon total">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ companyKanbanData.totalTasks }}</div>
                <div class="stat-label">总任务数</div>
              </div>
            </div>
            <div class="kanban-stat-item">
              <div class="stat-icon completed">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ companyKanbanData.completedTasks }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
            <div class="kanban-stat-item">
              <div class="stat-icon progress">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ companyKanbanData.inProgressTasks }}</div>
                <div class="stat-label">进行中</div>
              </div>
            </div>
            <div class="kanban-stat-item">
              <div class="stat-icon overdue">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ companyKanbanData.overdueTasks }}</div>
                <div class="stat-label">逾期任务</div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 图表分析区域 -->
      <div class="charts-section">
        <div class="charts-grid">
          <el-card class="chart-card" shadow="never">
            <template #header>
              <span class="card-title">任务指派分布</span>
            </template>
            <div ref="assigneePieChart" class="pie-chart"></div>
          </el-card>
          <el-card class="chart-card" shadow="never">
            <template #header>
              <span class="card-title">任务完成趋势</span>
            </template>
            <div ref="completionLineChart" class="line-chart"></div>
          </el-card>
        </div>
      </div>
      
      <div class="detail-sections">
        <el-row :gutter="16">
          <el-col :xs="24" :md="12">
            <el-card shadow="never" class="sub-card">
              <template #header><span class="sub-title">日程状态分布</span></template>
              <el-descriptions :column="2" size="small" border>
                <el-descriptions-item label="待办">{{ scheduleStatus.todo ?? 0 }}</el-descriptions-item>
                <el-descriptions-item label="进行中">{{ scheduleStatus.doing ?? 0 }}</el-descriptions-item>
                <el-descriptions-item label="已完成">{{ scheduleStatus.done ?? 0 }}</el-descriptions-item>
                <el-descriptions-item label="已取消">{{ scheduleStatus.canceled ?? 0 }}</el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-card shadow="never" class="sub-card">
              <template #header><span class="sub-title">Top 团队（近{{ days }}天按日程数）</span></template>
              <el-table :data="topTeams" size="small">
                <el-table-column prop="teamId" label="#" width="80" />
                <el-table-column prop="teamName" label="团队" />
                <el-table-column prop="worklogs" label="日程数" width="100" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="16" style="margin-top: 16px">
          <el-col :xs="24" :md="12">
            <el-card shadow="never" class="sub-card">
              <template #header><span class="sub-title">Top 用户（近{{ days }}天按日志数）</span></template>
              <el-table :data="topUsers" size="small">
                <el-table-column prop="userId" label="#" width="80" />
                <el-table-column prop="username" label="用户" />
                <el-table-column prop="worklogs" label="日志数" width="100" />
              </el-table>
            </el-card>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-card shadow="never" class="sub-card">
              <template #header><span class="sub-title">所有团队日程（近{{ days }}天）</span></template>
              <el-table :data="allTeamSchedules" size="small">
                <el-table-column prop="scheduleId" label="#" width="80" />
                <el-table-column prop="title" label="日程标题" />
                <el-table-column prop="teamName" label="所属团队" width="120" />
                <el-table-column prop="status" label="状态" width="80">
                  <template #default="{ row }">
                    <el-tag :type="getStatusType(row.status)" size="small">{{ getStatusText(row.status) }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始时间" width="160">
                  <template #default="{ row }">{{ formatDateTime(row.startTime) }}</template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="16" style="margin-top: 16px">
          <el-col :xs="24" :md="12">
            <el-card shadow="never" class="sub-card">
              <template #header><span class="sub-title">即将开始的日程（未来{{ days }}天）</span></template>
              <el-table :data="upcomingSchedules" size="small">
                <el-table-column prop="scheduleId" label="#" width="80" />
                <el-table-column prop="title" label="标题" />
                <el-table-column prop="status" label="状态" width="90" />
                <el-table-column prop="priority" label="优先级" width="90" />
                <el-table-column prop="startTime" label="开始时间" width="160" />
              </el-table>
            </el-card>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-card shadow="never" class="sub-card">
              <template #header><span class="sub-title">团队明细（近{{ days }}天日志）</span></template>
              <el-table :data="teamDetails" size="small">
                <el-table-column prop="teamId" label="#" width="80" />
                <el-table-column prop="teamName" label="团队" />
                <el-table-column prop="members" label="成员数" width="90" />
                <el-table-column prop="schedules" label="日程数" width="90" />
                <el-table-column prop="worklogs" label="日志数" width="90" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
        
        <!-- 全公司任务更新展示 -->
        <el-row :gutter="16" style="margin-top: 16px;">
          <el-col :span="24">
            <el-card shadow="never" class="sub-card">
              <template #header><span class="sub-title">最近任务更新</span></template>
              <div class="task-updates-list">
                <div v-if="companyTaskUpdates.length === 0" class="empty-state">
                  <el-empty description="暂无任务更新记录" :image-size="80" />
                </div>
                <div v-else class="updates-container">
                  <div v-for="update in companyTaskUpdates" :key="update.id" class="update-item">
                    <div class="update-avatar">
                      <el-avatar :size="32" :src="update.user?.avatar">
                        {{ update.user?.name?.charAt(0) || 'U' }}
                      </el-avatar>
                    </div>
                    <div class="update-content">
                      <div class="update-header">
                        <span class="user-name">{{ update.user?.name || '未知用户' }}</span>
                        <span class="update-action">{{ update.action }}</span>
                        <span class="task-title">{{ update.taskTitle }}</span>
                      </div>
                      <div class="update-meta">
                        <span class="team-name">{{ update.teamName }}</span>
                        <span class="update-time">{{ formatDateTime(update.timestamp) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, CircleCheck, Clock, Warning, Refresh } from '@element-plus/icons-vue'
import { api } from '@/utils/api'
import * as echarts from 'echarts'

const loading = ref(false)
const days = ref(7)
const stats = ref({ teamCount: 0, scheduleCount: 0, worklogCount: 0 })
const trend = ref([])
const teams = ref([])
const scheduleStatus = ref({})
const topTeams = ref([])
const topUsers = ref([])
const recentWorklogs = ref([])
const allTeamSchedules = ref([])
const upcomingSchedules = ref([])
const teamDetails = ref([])
const companyKanbanData = ref({
  totalTasks: 0,
  completedTasks: 0,
  inProgressTasks: 0,
  overdueTasks: 0
})
const companyTaskUpdates = ref([])
const assigneePieChart = ref(null)
const completionLineChart = ref(null)

const maxVal = computed(()=> Math.max(1, ...trend.value.map(t=>Number(t.worklogs||0))))
const scale = computed(()=> 80 / maxVal.value) // 最高条80px

async function load() {
  loading.value = true
  try {
    const data = await api.get('/metrics/admin', { days: days.value })
    stats.value = data?.stats || stats.value
    trend.value = Array.isArray(data?.trend) ? data.trend : []
    teams.value = Array.isArray(data?.teams) ? data.teams : []
  scheduleStatus.value = data?.scheduleStatus || {}
  // 优先使用后端返回的topTeamsByWorklogs，如果为空则使用公司看板数据中的团队统计
  topTeams.value = Array.isArray(data?.topTeamsByWorklogs) && data.topTeamsByWorklogs.length > 0 
    ? data.topTeamsByWorklogs 
    : []
  topUsers.value = Array.isArray(data?.topUsersByWorklogs) ? data.topUsersByWorklogs : []
  recentWorklogs.value = Array.isArray(data?.recentWorklogs) ? data.recentWorklogs : []
   upcomingSchedules.value = Array.isArray(data?.upcomingSchedules) ? data.upcomingSchedules : []
   teamDetails.value = Array.isArray(data?.teamDetails) ? data.teamDetails : []
  
  // 获取公司看板数据
  try {
    const kanbanData = await api.get('/team-metrics/company-kanban')
    companyKanbanData.value = {
      totalTasks: kanbanData.totalTasks || 0,
      completedTasks: kanbanData.statusCounts?.done || 0,
      inProgressTasks: kanbanData.statusCounts?.doing || 0,
      overdueTasks: kanbanData.statusCounts?.todo || 0,
      teamStats: kanbanData.teamStats || [],
      statusCounts: kanbanData.statusCounts || {}
    }
    
    // 如果topTeams为空，使用看板数据中的团队统计
    if (topTeams.value.length === 0 && companyKanbanData.value.teamStats.length > 0) {
      topTeams.value = companyKanbanData.value.teamStats
        .filter(team => team.totalTasks > 0)
        .sort((a, b) => b.totalTasks - a.totalTasks)
        .slice(0, 5)
        .map(team => ({
          teamId: team.teamId,
          teamName: team.teamName || `团队${team.teamId}`,
          worklogs: team.totalTasks // 使用任务数量作为工作日志数的替代
        }))
    }
  } catch (e) {
    console.error('获取公司看板数据失败:', e)
    companyKanbanData.value = {
      totalTasks: 0,
      completedTasks: 0,
      inProgressTasks: 0,
      overdueTasks: 0,
      teamStats: [],
      statusCounts: {}
    }
  }
  
  // 获取所有团队日程数据
  try {
    const schedulesData = await api.get('/team-metrics/managed-schedules', { limit: 50 })
    allTeamSchedules.value = Array.isArray(schedulesData?.schedules) ? schedulesData.schedules : []
  } catch (e) {
    console.error('获取团队日程数据失败:', e)
    allTeamSchedules.value = []
  }
  
  // 获取公司级别的任务更新记录
  try {
    const taskUpdatesData = await api.get('/team-metrics/company-task-updates', { limit: 20 })
    companyTaskUpdates.value = Array.isArray(taskUpdatesData?.taskUpdates) ? taskUpdatesData.taskUpdates : []
  } catch (e) {
    console.error('获取任务更新记录失败:', e)
    companyTaskUpdates.value = []
  }
  

  
  // 初始化图表
  await nextTick()
  initCharts()
  } catch (e) {
    ElMessage.error('加载失败：' + (e.message||''))
  } finally {
    loading.value = false
  }
}

async function refreshKanbanData() {
  try {
    const data = await api.get('/team-metrics/company-kanban')
    companyKanbanData.value = {
      totalTasks: data.totalTasks || 0,
      completedTasks: data.statusCounts?.done || 0,
      inProgressTasks: data.statusCounts?.doing || 0,
      overdueTasks: data.statusCounts?.todo || 0,
      teamStats: data.teamStats || [],
      statusCounts: data.statusCounts || {}
    }
    
    // 如果topTeams为空，使用看板数据中的团队统计
    if (topTeams.value.length === 0 && companyKanbanData.value.teamStats.length > 0) {
      topTeams.value = companyKanbanData.value.teamStats
        .filter(team => team.totalTasks > 0)
        .sort((a, b) => b.totalTasks - a.totalTasks)
        .slice(0, 5)
        .map(team => ({
          teamId: team.teamId,
          teamName: team.teamName || `团队${team.teamId}`,
          worklogs: team.totalTasks // 使用任务数量作为工作日志数的替代
        }))
    }
    
    // 同时刷新任务更新数据
    const taskUpdatesData = await api.get('/team-metrics/company-task-updates', { limit: 20 })
    companyTaskUpdates.value = Array.isArray(taskUpdatesData?.taskUpdates) ? taskUpdatesData.taskUpdates : []
    
    // 重新初始化图表
    await nextTick()
    initCharts()
    
    ElMessage.success('数据已刷新')
  } catch (e) {
    ElMessage.error('刷新失败：' + (e.message || ''))
  }
}

function initCharts() {
  // 初始化任务指派分布饼图
  if (assigneePieChart.value) {
    const pieChart = echarts.init(assigneePieChart.value)
    
    // 使用后端返回的团队统计数据
    let pieData = []
    if (companyKanbanData.value.teamStats && Array.isArray(companyKanbanData.value.teamStats)) {
      pieData = companyKanbanData.value.teamStats
        .filter(team => team.totalTasks > 0)
        .slice(0, 8) // 只显示前8个团队
        .map(team => ({
          value: team.totalTasks,
          name: team.teamName || `团队${team.teamId}`
        }))
    }
    
    // 如果没有团队数据，使用状态分布
    if (pieData.length === 0) {
      pieData = [
        { value: companyKanbanData.value.completedTasks, name: '已完成' },
        { value: companyKanbanData.value.inProgressTasks, name: '进行中' },
        { value: companyKanbanData.value.overdueTasks, name: '待办' }
      ].filter(item => item.value > 0)
    }
    
    const pieOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      series: [{
        name: '任务分布',
        type: 'pie',
        radius: '50%',
        data: pieData
      }]
    }
    pieChart.setOption(pieOption)
  }
  
  // 初始化任务完成趋势折线图
  if (completionLineChart.value) {
    const lineChart = echarts.init(completionLineChart.value)
    
    // 基于任务更新数据生成近7天的趋势数据
    const today = new Date()
    const trendData = []
    const dateLabels = []
    
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(date.getDate() - i)
      const dateStr = date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' })
      dateLabels.push(dateStr)
      
      // 统计该日期完成的任务数量
      const dayCompletedTasks = companyTaskUpdates.value.filter(update => {
        if (!update.timestamp) return false
        const updateDate = new Date(update.timestamp)
        return updateDate.toDateString() === date.toDateString() && 
               (update.action === '完成了任务' || update.status === 'done')
      })
      
      trendData.push(dayCompletedTasks.length)
    }
    
    // 如果没有数据，使用状态统计数据生成简单趋势
    if (trendData.every(val => val === 0) && companyKanbanData.value.completedTasks > 0) {
      const avgCompleted = Math.floor(companyKanbanData.value.completedTasks / 7)
      for (let i = 0; i < 7; i++) {
        trendData[i] = avgCompleted + Math.floor(Math.random() * 3) - 1
      }
    }
    
    const lineOption = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}: {c}个任务'
      },
      xAxis: {
        type: 'category',
        data: dateLabels
      },
      yAxis: {
        type: 'value',
        minInterval: 1
      },
      series: [{
        name: '完成任务数',
        type: 'line',
        data: trendData,
        smooth: true,
        lineStyle: {
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        }
      }]
    }
    lineChart.setOption(lineOption)
  }
}

function formatDateTime(timestamp) {
   if (!timestamp) return '-'
   return new Date(timestamp).toLocaleString('zh-CN')
 }
 
 function getStatusType(status) {
   const statusMap = {
     'todo': '',
     'doing': 'warning',
     'done': 'success',
     'canceled': 'danger'
   }
   return statusMap[status] || ''
 }
 
 function getStatusText(status) {
   const statusMap = {
     'todo': '待办',
     'doing': '进行中',
     'done': '已完成',
     'canceled': '已取消'
   }
   return statusMap[status] || status
 }

onMounted(load)
</script>

<style scoped>
.admin-page { padding: 24px; background: #f5f7fa; min-height: 100vh; }
.content-card { border-radius: 12px; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.card-title { font-size: 18px; font-weight: 600; color: #303133; }
.kpi-card { text-align:center }
.kpi-num { font-size:28px; font-weight:700; }
.kpi-title { color:#6b7280; margin-top:6px }
.trend-wrap { margin-top: 20px; }
.trend-title { font-weight: 600; margin-bottom: 8px; }
.bars { display:flex; gap:8px; align-items:flex-end; height: 110px; }
.bar { display:flex; flex-direction:column; align-items:center; gap:6px; }
.bar-col { width: 18px; background:#409eff; border-radius:4px; transition:height .2s; }
.bar-label { font-size:12px; color:#6b7280 }
.teams-wrap { margin-top: 20px; }

/* 公司看板样式 */
.company-kanban-section { margin: 20px 0; }
.kanban-card { border-radius: 8px; }
.kanban-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; }
.kanban-stat-item { display: flex; align-items: center; padding: 16px; border-radius: 8px; background: #f8f9fa; transition: all 0.3s ease; }
.kanban-stat-item:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
.stat-icon { width: 48px; height: 48px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-right: 12px; font-size: 20px; }
.stat-icon.total { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
.stat-icon.completed { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; }
.stat-icon.progress { background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%); color: #d68910; }
.stat-icon.overdue { background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%); color: #e74c3c; }
.stat-content .stat-value { font-size: 24px; font-weight: bold; margin-bottom: 4px; color: #303133; }
.stat-content .stat-label { font-size: 14px; color: #909399; }

/* 图表区域样式 */
.charts-section { margin: 20px 0; }
.charts-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 16px; }
.chart-card { border-radius: 8px; }
.pie-chart, .line-chart { height: 300px; width: 100%; }

/* 任务更新样式 */
.task-updates-list { max-height: 400px; overflow-y: auto; }
.updates-container { display: flex; flex-direction: column; gap: 12px; }
.update-item { display: flex; align-items: flex-start; padding: 12px; border-radius: 8px; background: #f8f9fa; transition: all 0.3s ease; }
.update-item:hover { background: #e9ecef; }
.update-avatar { margin-right: 12px; flex-shrink: 0; }
.update-content { flex: 1; }
.update-header { margin-bottom: 4px; }
.user-name { font-weight: 600; color: #303133; margin-right: 8px; }
.update-action { color: #409eff; margin-right: 8px; }
.task-title { color: #606266; font-weight: 500; }
.update-meta { display: flex; align-items: center; gap: 12px; font-size: 12px; color: #909399; }
.team-name { background: #e1f3ff; color: #409eff; padding: 2px 6px; border-radius: 4px; }
.empty-state { text-align: center; padding: 40px 20px; }

.detail-sections { margin-top: 16px; }
.sub-card { margin-bottom: 12px; }
.sub-title { font-weight: 600; }
</style>